<template>
  <div class="c-bg-sgray">
    <audio id="audio" @ended="playAudioEnd" class="c-pf c-p-l-100"></audio>
    <div class="c-ph24 c-pv22 c-bg-white">
      <div class="c-fs28 c-fc-xblack" v-if="topData.name">{{topData.name}}</div>
      <div class="c-fs22 c-fc-gray c-pt10 c-pb20">
        {{workType == 3 ? '第'+ topData.reorder +'课时': (workType == 1 ? topData.startDay : topData.startTime +' 至 '+ topData.endTime)}}
      </div>
      <section class="c-p" v-if="topData.cover">
        <img class="c-w100" :src="$addXossFilter(topData.cover)" alt="" />
      </section>
      <!-- 课程介绍 -->
      <clock-course-detail-com v-if="topData.description &&topData.description.length > 0 &&(topData.description.length == 1? topData.description[0].content != '': true)"
        :isShowTheme='topData.isShowTheme'  :status="topData.status" :description="topData.description" @clickShowVideo="clickShowVideo"></clock-course-detail-com>
    </div>
    <div class="c-mt30 c-ph24">
      <div class="c-flex-row c-justify-sb c-aligni-center">
        <div class="c-fw600 c-fs28 c-fc-xblack">全部日记</div>
        <new-clock-search-bar :isShowbutton="false" :placeholder="'请输入关键字搜索'"  :selectList="selectList" @search="startSearch"></new-clock-search-bar>
      </div>
      <div class="c-bg-white c-br20 c-pt20 c-pb24 c-mt20 c-p" v-for="(item, index) in studentWorkList" :key="index" @click.stop="goStuAnswerResult(item)">
        <i v-if="item.examType == 3" class="iconfont c-pa c-p-t0 c-fs c-p-r24 c-fs24 c-p-r100 c-fc-green">&#xe829;</i>
        <div v-if="item.enableShow==0&&isDisCheat==2" class="c-fs48 theme-fc iconfont icon-biaoqianx c-pa onlyIcon">
          <div class="c-fc-white c-fs18 c-pa c-p-t5 c-p-l20">仅老师可见</div>
        </div>
        <div class="c-flex-row c-pl20 c-p">
          <img @click.stop="clickGoStudyHistory(item.userId)" class="c-ww60 c-hh60 c-brp50" :src="$addXossFilter(item.headimgurl, require('../../../assets/defult_head.png'))" alt="" />
          <div class="c-pl20 c-flex-grow1 c-w0">
            <div class="c-fs24 c-flex-row c-aligni-center c-justify-sb">
              <div class="c-flex-row">
                <span class="c-pr20 c-maxw160 c-text-ellipsis1 c-fs20 c-fw600">{{ item.nickname }}</span>
                <span v-if="item.isTop" class="c-fs18 c-ww60 c-flex-row c-lh c-flex-center theme-bg c-fc-white c-br6 c-mr12">置顶</span>
                <span v-if="item.isHot" class="c-fs18 c-ww60 c-flex-row c-lh c-flex-center theme-fc theme-bd1 theme-bg-10 c-br6">精选</span>
              </div>
            </div>
            <div class="c-flex-row c-aligni-center c-pt12">
              <div v-if="item.type == 1 && item.rank !== null&& item.rank!=0" class="c-flex-row c-flex-center">
                <img v-for="index in 5" :key="index" class="c-ww24 c-hh24 c-mr4" :src="
                  index <= item.rank
                    ? require('@/assets/i/wap/clockIn/star_s.png')
                    : require('@/assets/i/wap/clockIn/star_d.png')
                " alt="" />
              </div>
              <span v-if="item.type == 1 && item.rank !== null && item.rank!=0" class="theme-fc c-pl10 c-pr10 c-fs20">{{ item.rank * 20 }}分</span>
              <div v-if="workType == 1" class="c-fs18 c-fc-gray">
                已打卡{{ item.finishNum }}天
              </div>
              <div v-else-if="workType == 2" class="c-fs18 c-fc-gray">
                已完成{{ item.finishNum }}个作业
              </div>
              <div v-else class="c-fs18 c-fc-gray">
                已打卡{{ item.finishNum }}课时
              </div>
            </div>
          </div>
        </div>
        <clock-aswer-content
          @clickCom="clickCom"
          @clickZan="clickZan"
          @clickPlayAudio="clickPlayAudio"
          @clickShowVideo="clickShowVideo"
          :isAnalyze="0"
          :playAduioSrc="playAduioSrc"
          :homeworkType="item.type"
          :aswerInfo="item"
          :aswerIndex="index"
          :isTeacher="topData.isTeacher">
        </clock-aswer-content>
      </div>
      <loading-status-tem :dataStatus="dataStatus" noDataText="暂无打卡日记"></loading-status-tem>
    </div>
    <clock-tea-comment-com :curSelectDate="curTime" :curId="hwId" :clockInId="clockInId" :teacher="1" :enableLongAudio='enableLongAudio' :playAduioSrc="playAduioSrc" :showTeaCommentModal="showTeaCommentModal" :workType="workType" :resultIndex="resultIndex" :resultInfo="resultInfo" :imgData="imgData"
      @commentSuccess="commentSuccess" @clickPlayAudio="clickPlayAudio" @clickShowVideo="clickShowVideo" @cleanPlayAudioUrl="cleanPlayAudioUrl"></clock-tea-comment-com>
    <!-- 非教师评论 -->
    <clock-comment-com :enableLongAudio='enableLongAudio' @clickShowVideo="clickShowVideo" :comType="comType" :isTeacher="topData.isTeacher" :playAduioSrc="playAduioSrc" :showCommentModal="showComInput" :inputCom="inputCom" :replyName="replyName"
      :curComId="curComId" :replyId="replyId" :commentId='commentId' :imgData="imgData" @commentSuccess="commentSuccess" @clickPlayAudio="clickPlayAudio" @cleanPlayAudioUrl="cleanPlayAudioUrl"></clock-comment-com>
    <!-- 视频播放器 -->
    <video-popup :showVideo="showVideo" @clickCloseVideo="clickCloseVideo" :videoSrc="currentVideoObj.videoSrc" :m3u8Url="currentVideoObj.m3u8Url"></video-popup>
  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import NewClockSearchBar from "@/components/templates/common/newClockSearchBar.vue";
import videoPopup from "@/components/templates/common/videoPopup.vue";
import ClockCourseDetailCom from "@/components/templates/clockIn/clockCourseDetailCom.vue";
import clockTeaCommentCom from "@/components/templates/clockIn/clockTeaCommentCom.vue";
import clockAswerContent from "@/components/templates/clockIn/clockAswerContent.vue";
import clockCommentCom from "@/components/templates/clockIn/clockCommentCom.vue";
import {
  utilJs
} from "@/utils/common.js";
let LIMIT = 10
let isLoading = false;
let curComIndex = ""; //当前评论的下标
let hasRead = '';//推送来源
export default {
  name: "HomeworkDiary",
  components: {
    loadingStatusTem,
    NewClockSearchBar,
    videoPopup,
    ClockCourseDetailCom,
    clockTeaCommentCom,
    clockAswerContent,
    clockCommentCom
  },
  props: [],
  data() {
    return {
      curScollTop:0,
      curScollTopFlag:true,
      dataStatus: 'HAS_MORE_DATA',
      selectList: [["昵称", "内容"]],
      workType:1,
      clockInId:'',
      topData:'',
      searchType:'', //搜索类型 1=用户 2=打卡内容
      searchName:'', //搜索的内容
      startDay:'',
      page:1,
      playAduioSrc: "",
      resultInfo: {},
      resultIndex: -1,
      showTeaCommentModal: false, //显示教师评论输入框
      showVideo: false, //显示视频播放器
      currentVideoObj:'',
      imgData: {},
      replyName: "", //回复人的ID
      inputCom: "", //评论的输入内容
      replyId: "", //回复人的昵称
      commentId:'',
      studentWorkList:[],
      showComInput:false,
      comType: 1, //是否教师评论教师
      curTime:'',
      isDisCheat:0,
      enableLongAudio:0
    };
  },
  created() {
    utilJs.appShare(this);
  },
  beforeRouteLeave(to, from, next) {
    //当有评论弹窗的时候，后退就关闭弹窗,因为后退会把history历史栈后退一个，所以要添加回去
    if (
      (this.showComInput || this.showTeaCommentModal || this.showVideo) &&
      to.path != "/" &&
      to.path != "/homePage/spread/spreadIndex" &&
      to.path != "/member/vip/vipUpNew"
    ) {
      this.showTeaCommentModal = false;
      this.showComInput = false;
      if (this.showVideo) {
        this.showVideo = false;
      }
      history.pushState(
        null,
        null,
        `${window.location.href.split("#")[0]}#${from.fullPath}`
      );
    } else {
      next();
    }
  },
  methods: {
    getBaseConfig() {
      let postUrl = `${global.apiurl}signCard/getBaseConfig?signColId=${this.clockInId}`;
      utilJs.getMethod(postUrl, (res) => {
        this.isDisCheat = res.isDisCheat
        this.enableLongAudio = res.enableLongAudio
      });
    },
    //学习记录
    clickGoStudyHistory(userId) {
      if (this.bindPhoneSetting && this.bindPhoneSetting.getBind) {
        if (utilJs.goBindMobile()) return;
      }
      this.$routerGo(this, "push", {
        path: "/homePage/clockIn/studyHistory",
        query: {
          clockId: this.clockInId,
          userId: userId || this.topData.userId,
          isMe: !userId,
        }
      });
    },
    //监听音频播放结束执行的内容
    playAudioEnd() {
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
    },
    cleanPlayAudioUrl() {
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
    },
     //评论成功
    commentSuccess(comData, type) {
      let content = {
        type: comData.type,
        content: comData.content,
        nickname: comData.nickname,
        replyName: this.replyName,
        replyUserId: this.replyId,
        userId: this.topData.userId,
        imgArr: comData.imgArr,
        audioArr: comData.audioArr,
        videoArr: comData.videoArr || [],
        headimgurl:comData.headimgurl,
        commentId:comData.commentId,
        encodeUserId:localStorage.getItem("userId"),
        createdAt:comData.commentTime,
      };
      //评论别人
      if (comData.teacherCom) {
        //老师点评
        this.$set(this.studentWorkList[curComIndex], "isHot", comData.isHot);
        this.$set(this.studentWorkList[curComIndex], "rank", comData.rank);
        this.$set(this.studentWorkList[curComIndex], "createdAt", comData.commentTime);
      }
      if (comData.teacherCom && this.sortType == 5) {
        //老师点评，当前类型是未点评，则把当前点评的这条数据移除掉
        this.studentWorkList.splice(curComIndex, 1);
      } else {
        this.studentWorkList[curComIndex].commentArr.push(content);
      }
      this.commentId = content.commentId
      this.showTeaCommentModal = false;
      this.showComInput = false;
      this.replyName = "";
      this.inputCom = "";
      this.replyId = "";
      if (type == 1) {
        this.studentListAll()
        return
      }
    },
    //点击开始播放音频
    clickPlayAudio(audioUrl) {
      if (this.playAduioSrc == audioUrl) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        return;
      }
      this.playAduioSrc = audioUrl;

      //返回mp3则用audio播放
      if (this.playAduioSrc) {
        document.getElementById("audio").src = this.playAduioSrc;
        //document.getElementById("audio").play();
        utilJs.audioPlayFun(document.getElementById("audio"), "play");
      }
    },
    //点赞
    clickZan(index, myAswerIndex) {
      if (isLoading) {
        return;
      }
      isLoading = true;
      //点赞自己
      let zanType = 0;
      let examMainId = "";
        zanType = this.studentWorkList[index].hasZan == 1 ? 2 : 1;
        examMainId = this.studentWorkList[index].examMainId;

      utilJs.getMethod(
        `${global.apiurl}signCard/clickZan/${examMainId}?zanType=${zanType}`,
        (res) => {
          isLoading = false;
          if (res.status == 1) {
            this.$showCjToast({
              text: zanType == 1 ? "点赞成功" : "取消点赞",
              type: "success",
            });
              //点赞别人
              console.log(index, zanType)
              this.$set(
                this.studentWorkList[index],
                "hasZan",
                zanType == 2 ? 0 : 1
              );
              if (zanType == 1) {
                this.studentWorkList[index].zanMan.push({
                  nickname: res.nickname,
                  userId:res.userId
                });
              } else {
                let zanArr = this.studentWorkList[index].zanMan.filter((item) => {
                  return item.userId != res.userId;
                });
                this.$set(this.studentWorkList[index], "zanMan", zanArr);
              }
          } else if (res.status == 2) {
            this.$showCjToast({
              text: res.message,
              type: "warn",
            });
          } else {
            this.$showCjToast({
              text: '操作失败',
              type: "warn",
            });
          }
        },
        (failRes) => {
          isLoading = false;
        }
      );
    },
    /**
     * 点击评论
     * index： -1 评论自己，其他:评论别人
     * cIndex： -1 评论别人的内容，其他：评论别人的评论
     */
    clickCom(index, cIndex, commentId, myAswerIndex) {
      if (cIndex == -1 && this.topData.isTeacher == 1) {
        curComIndex = index;
        this.resultInfo = this.studentWorkList[index];
        this.resultIndex = index;
        this.showTeaCommentModal = true;
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        return;
      }
      console.log(index, cIndex)
      this.commentId = commentId
      let examMainId = "";
        //点击别人的评论
      if (cIndex != -1) {
        this.comType = this.studentWorkList[index].commentArr[cIndex].type;
      }
      examMainId = this.studentWorkList[index].examMainId;
      this.replyId =
        cIndex == -1
          ? ""
          : this.studentWorkList[index].commentArr[cIndex].userId;
      this.replyName =
        cIndex == -1
          ? ""
          : this.studentWorkList[index].commentArr[cIndex].nickname;
      curComIndex = index;
      if (this.curComId != examMainId) {
        this.inputCom = "";
      }
      this.curComId = examMainId;
      this.showComInput = true;
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
    },
    studentListAll() {
      this.page = 1; //页数
      this.searchType = ''; //搜索类型 1=用户 2=打卡内容
      this.searchName = ''; //搜索的内容
      this.studentWorkList = [];
      this.dataStatus = "HAS_MORE_DATA";
      this.studentList()
    },
    startSearch(searchText) {
      this.searchName = searchText.searchValue;
      let si = searchText.selectItem;
      this.page = 1;
      if (si == "昵称") {
        this.searchType = 1
      } else if (si == "内容") {
        this.searchType = 2
      }
      this.studentList();
    },
    studentList() {
      if (this.dataStatus == "LOADING") {
        return;
      }
      this.dataStatus = "LOADING";
      let getUrl = `signCard/teacherReadSubmit?signColId=${this.clockInId}&limit=${LIMIT}&page=${this.page}&hwId=${this.hwId}&hasRead=${hasRead}
      &searchType=${this.searchType}&searchName=${this.searchName}&startDay=${this.startDay}`
      utilJs.getMethod(
        global.apiurl + getUrl,
        (res) => {
          if (this.page == 1) {
            this.studentWorkList = res.studentList.data
          } else {
            this.studentWorkList = [...this.studentWorkList, ...res.studentList.data];
          }
          if (res.studentList.data && (res.studentList.data.length < LIMIT)) {
            this.dataStatus = this.page == 1 && res.studentList.data.length == 0 ? "NO_DATA" : "NO_MORE_DATA";
          } else {
            this.dataStatus = "HAS_MORE_DATA";
            this.page++;
          }
          this.$nextTick(() => {
            window.scrollTo(0, this.curScollTop);
            if (this.curScollTop == (document.documentElement.scrollTop || document.body.scrollTop)) {
              this.curScollTopFlag = true
            }
          })
        },
        (failRes) => {
          this.dataStatus = "DATA_ERROR";
        }
      );
    },
    //点击显示视频
    clickShowVideo(videoSrc, m3u8Url) {
      this.showVideo = true;
      this.currentVideoObj = {videoSrc, m3u8Url}
    },
    //点击关闭视频
    clickCloseVideo() {
      if (this.showVideo) {
        this.showVideo = false;
      }
    },
    // 获取头部打卡信息
    topDetail() {
      let getUrl = `signCard/teacherHomeworkDetail?signColId=${this.clockInId}&hwId=${this.hwId}&startDay=${this.startDay}`
      utilJs.getMethod(
        global.apiurl + getUrl,
        (res) => {
          if (res.length == 0) {
            this.$routerGo(this, "replace", {
              path: "/homePage/clockIn/clockInDetail",
              query: {
                clockInId: this.clockInId
              }
            });
          }
          this.topData = res
          if (this.workType != 3) {
            if (this.workType == 1) {
              this.topData.startDay = this.topData.startDay.split(' ')[0]
            } else {
              // this.topData.startTime = this.topData.startTime
              // this.topData.endTime = this.topData.endTime
            }
          }
          this.wechatShare();
        }
      );
    },
    goStuAnswerResult(info) {
      this.$routerGo(this, "push", {
        path: "/homePage/clockIn/stuShortAnswerResult",
        query: {
          clockInId: this.clockInId,
          // curHwId : this.homeWorkInfo.hwId,
          stuHwId:info.hwId,
          curSelectDate:info.startDay ? info.startDay.split(' ')[0] : '',
          examMainId: info.examMainId,
          totalNum:info.type == 3 ? info.aiNum : 0
        }
      });
    },
    //分享
    wechatShare() {
      let title = this.topData.shareTitle;
      let shareImg = this.topData.sharePic;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/clockIn/clockInDetail?clockInId=${this.clockInId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.topData.shareDesc || "点击查看详情";
      let shareData = {
        title: title,
        shareImg: shareImg,
        shareUrl: shareUrl,
        shareDesc: shareDesc
      };
      localStorage.setItem("homeWorkShareInfo", JSON.stringify(shareData));
      utilJs.wechatConfig(
        shareUrl,
        title,
        shareImg,
        shareDesc,
        function () { },
        true
      );
    },
    //手机端分享
    appShare() {
      let title = this.topData.name;
      let shareImg = this.topData.sharePic;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/clockIn/clockInDetail?clockInId=${this.clockInId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.topData.shareDesc || "点击查看详情";
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
    windowScrollFunction() {
      if (this.curScollTopFlag) {
        this.curScollTop = document.documentElement.scrollTop || document.body.scrollTop;
      }
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA') {
         this.studentList();
        }
      });
    },
  },
  mounted() {
    setDocumentTitle("打卡");// eslint-disable-line
    this.dataStatus = 'HAS_MORE_DATA';
    this.clockInId = this.$route.query.clockInId
    this.hwId = this.$route.query.hwId
    this.curTime = this.$route.query.curTime
    this.startDay = this.$route.query.startDay
    this.workType = this.$route.query.workType
    hasRead = this.$route.query.hasRead || "";
    this.playAduioSrc = "";
    if (document.getElementById("audio")) {
      document.getElementById("audio").src = "";
    }
    this.topDetail()
    this.studentListAll()
    this.getBaseConfig()
    window.addEventListener('scroll', this.windowScrollFunction);
    //解决ios播放没声音
    this.$nextTick(function () {
      try {
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              function () {
                document.getElementById("audio").play();
              },
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", function () {
              document.getElementById("audio").play();
            });
            document.attachEvent("onWeixinJSBridgeReady", function () {
              document.getElementById("audio").play();
            });
          }
          WeixinJSBridge.invoke("getNetworkType", {}, function (e) {
            // eslint-disable-line
            // 在这里拿到 e.err_msg, 这里面就包含了所有的网络类型
            document.getElementById("audio").play();
            console.log(
              "WeixinJSBridgeWeixinJSBridgeWeixinJSBridgeWeixinJSBridge"
            );
          });
        }
      } catch (error) {
        // continue regardless of error
      }
    });
  },
  destroyed() {
    this.curScollTopFlag = false
    this.dataStatus = 'NO_MORE_DATA';
    this.playAduioSrc = "";
    if (document.getElementById("audio")) {
      document.getElementById("audio").src = "";
    }
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.teaHeadbg {
  background: url("../../../assets/i/wap/clockIn/teaHeadBg.png");
  background-size: 100%;
}
.c-ml-4{
  margin-left: -0.4rem ;
}
.timeEnd{
  top: -0.3rem;
  right: -0.3rem;
}
.onlyIcon{
  left: -0.26rem;
  top: -.5rem;
}
</style>
